<?php
/**
 * Easthv Zend Framework Project
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Easthv_Controller
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * Bootstrap
 * 
 * @uses       Zend_Application_Bootstrap_Bootstrap
 * @category   Zend
 * @package    
 * @subpackage 
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    private $_baseUrl = '';
	
	private $_debug = false;
	
	private $_allowFormats = array('html', 'js', 'jsonp', 'xml');

	private $_hostmapping = false;

	/*
	protected $_modules = array(
		'default' => array(),
		'apiv1' => array(
			'routerType' => 'domain',
			'routerKey' => 'api',
		),	
	);

	protected function _initFrontModules() {
		$this->bootstrap('frontController');
		$front = $this->getResource('frontController');
		$front->addModuleDirectory(APPLICATION_PATH . '/default');
		$front->addModuleDirectory(APPLICATION_PATH . '/api/v1');
	}
	 */


	/**
	 * Bootstrap autoloader for application resources
	 * 
	 * @return Zend_Application_Module_Autoloader
	 */
	protected function _initAutoload()
	{
		$autoloader = new Zend_Application_Module_Autoloader(array(
			'namespace' => 'Easthv',
			'basePath'  => dirname(__FILE__),
		));

		Zend_Registry::set('lang', 'en');
		require_once APPLICATION_PATH . '/controllers/BasicController.php';

		return $autoloader;
	}

	/**
	 * Initialize system config
	 * 
	 * @return void
	 */
	protected function _initConfig()
    {
        $config = $this->getOptions();
        Zend_Registry::set('config', $config);
        $this->_baseUrl = $config['resources']['frontController']['baseUrl'];
		$this->_debug = $config['system']['debug'];

		$this->_hostmapping = $config['system']['hostmapping']['enable'] ? $config['system']['hostmapping']['route'] : false;
		return $config;
    }
    
    /**
     * Initialize system router
     * 
     * @return void
     */
    protected function _initRouter()
    {
		$front = Zend_Controller_Front::getInstance();

        //Init http requests, for fixing request format. or else http request will init in Zend_Rest_Route
        $front->setRequest(new Zend_Controller_Request_Http());

        $router = $front->getRouter();

        //init main router
        $chainedRoute = new Zend_Controller_Router_Route_Chain();


        //Router rewrite additions
        $additions = array(
            //default format is HTML
            'format' => 'html',
        );

        //hostname router
		$domainString = $_SERVER['HTTP_HOST'];
        $domain = explode('.', $domainString);
        if(isset($domain[2])) {
            $length = count($domain) - 3;

            for($i = 0; $i <= $length; $i++) {
                $domain[$i] = $i === $length ? ':domain' : ':domain' . ($length - $i);
            }
        
            $chainedRoute->chain(new Zend_Controller_Router_Route_Hostname(
                implode('.', $domain)
            ));

            $additions['hostname'] = $domain[$length + 1] . '.' . $domain[$length + 2];

        }

        //Request Format Parse Start
        $requestUri = $front->getRequest()->getRequestUri();
        $arrUrl = parse_url($_SERVER['REQUEST_URI']);
        $queryString = $arrUrl['query'];
		$requestUri = $queryString ? substr($requestUri, 0, -strlen($queryString)-1) : $requestUri;
        $requestUri = $this->_baseUrl ? substr($requestUri, strlen($this->_baseUrl)) : $requestUri;
        $front->getRequest()->setRequestUri($requestUri);

        //only root path , do nothing
        if($requestUri !== '/'){

            //no extension mark, do nothing
            $ext = strstr($requestUri, '.');
            if($ext !== false && strpos($ext, '/') === false) {

                $requestUri = explode('/', $requestUri);
                $urlPathLevel = count($requestUri) - 1;

                switch($urlPathLevel) {
                
                //url looks like http://example.com/index.xml
                case 1:
                    list($additions['controller'], $additions['format']) = explode('.', $requestUri[1]);
                    
                    //fix Zend_Rest_Route
                    $front->getRequest()->setPathInfo($additions['controller']);
                    break;
                    
                //url looks like http://example.com/index/abc.xml
                case 2:
                    list($additions['id'], $additions['format']) = explode('.', $requestUri[2]);
                    $front->getRequest()->setPathInfo($requestUri[1] . '/' . $additions['id']);
                    break;
                    
                //url looks like http://example.com/index/path1/path2/abc.xml
                default:
                    if($urlPathLevel % 2 === 0) {
                        break;
                    }

                    list($additions[$requestUri[$urlPathLevel - 1]], $additions['format']) = explode('.', $requestUri[$urlPathLevel]);
                    $requestUri[$urlPathLevel] = $additions[$requestUri[$urlPathLevel - 1]];
                    $front->getRequest()->setPathInfo(implode('/', $requestUri));
                }
            }
        }

        //Fixing url like /abc/def...
        if(!$additions['format'] || !in_array($additions['format'], $this->_allowFormats)){
            $additions['format'] = 'html';
		}

        //Request Format Parse End
        $restRoute = new Zend_Rest_Route($front, $additions);
        $chainedRoute->chain($restRoute);


		$moduleName = 'default';

		if(false !== $this->_hostmapping) {
			foreach($this->_hostmapping as $hostRouteName => $hostinfo) {
				if($domainString == $hostinfo['domain']) {
					$moduleName = $hostinfo['module'];
					$moduleRoute = new Zend_Controller_Router_Route_Module(array('module' => $moduleName));
					$chainedRoute->chain($moduleRoute);	
					break;			
				}
			}

		}
		$router->addRoute($moduleName, $chainedRoute);

		//require_once APPLICATION_PATH . '/modules/admin/controllers/AbstractController.php';
		$front->additionalRequests = $router->getRoute($moduleName)->_request->getParams();
		return $router;
    }



    /**
     * Initialize ZFDebug
     * 
     * @return void
     */
    protected function _initZFDebug()
    {
        if($this->_debug < 2){
            return;
        }

        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('ZFDebug');
 
        $options = array(
            'plugins' => array(
                //'Variables',
                'File' => array('base_path' => realpath(APPLICATION_PATH . '/../')),
                'Memory',
                'Time',
                //'Registry',
                'Exception',
                'Html',
        ));
 
        # Instantiate the database adapter and setup the plugin.
        # Alternatively just add the plugin like above and rely on the autodiscovery feature.
        if ($this->hasPluginResource('db')) {
            $this->bootstrap('db');
            $db = $this->getPluginResource('db')->getDbAdapter();
            $options['plugins']['Database']['adapter'] = $db;
        }
 
		# Setup the cache plugin
		if ($this->hasPluginResource('cache')) {
			$this->bootstrap('cache');
			$cache = $this-getPluginResource('cache')->getDbAdapter();
			$options['plugins']['Cache']['backend'] = $cache->getBackend();
		}


		$debug = new Zend_Easthv_Debug($options);

		$this->bootstrap('frontController');
		$frontController = $this->getResource('frontController');
		$frontController->registerPlugin($debug);
	}


}
